<template>
  <div>
    <div class="node" v-has="{action: 'personal:repair:list', effect: 'move'}">
      <div :class="[$style.search_box, $style.topSelect]">
        <SearchInput
          placeholder="输入手机号"
          label="请输入"
          style="margin-right:20px"
          :value="phone"
          :onChange="(val) => changeSearch('phone',val)"
          :onBlur="queryData"
        />
        <div :class="$style.selectBox">
          <label>选择站点：</label>
            <el-select
              style="width:200px"
              v-model="siteId"
              clearable
              @change="queryData(siteId)"
              placeholder="选择站点">
              <el-option v-for="item in siteList" :key="item.id" :label="item.name" :value="item.id+''"></el-option>
            </el-select>
        </div>
        <div :class="$style.selectBox">
          <label>选择状态：</label>
            <el-select
              style="width:200px"
              v-model="state"
              clearable
              @change="queryData(state)"
              placeholder="选择状态">
              <el-option v-for="item in stateList" :key="item.id" :label="item.name" :value="item.id+''"></el-option>
            </el-select>
        </div>
        <div :class="$style.selectBox" style="display: flex;align-items: center;">
          <label>时间：</label>
          <el-date-picker
            v-model="appointmentTime"
            type="datetimerange"
            @change="queryData"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            :picker-options="pickerOptions"
            style="height:40px"
          ></el-date-picker>
        </div>
        <div :class="$style.searchBox1" style="margin-left: 20px">
          <el-button type="primary" @click="queryData">查询</el-button>        
        </div>
      </div>
      <Panel title="充电桩维修工单" :intro='intro'>
        <div slot='ext' :class="$style.examine">
          <!-- <div class="adopt" @click="()=>edit()">新增</div> -->
      </div>
      <TableEncapsulation
        slot="body"
        :tableConfig="tableConfig"
        :tableData="tableData"
      >
      <template slot="operation" slot-scope="operation">
            <el-button
              v-has="{action: 'personal:repair:handle', effect: 'move'}"
              
              v-if="operation.row.state == 0"
              @click="()=>edit(operation.row, 1)"
            >处理</el-button>
            <el-button
              v-has="{action: 'personal:repair:complete', effect: 'move'}"
              
              v-if="operation.row.state == 1"
              @click="()=>edit(operation.row, 2)"
            >维修完成</el-button>
          </template>
          <TablePager
            slot="pager"
            v-if="pager.use"
            :size="pager.size"
            :pageChange="pageChange"
            :show-total="pager.showTotal"
            :total="pager.total"
            :current="pager.current"
          >
            <span class="demonstration">GO></span>
          </TablePager>
      </TableEncapsulation>
      </Panel>

      <ModalPanel
      :visible='visible'
        title="编辑"
        :onCancel="onCancel"
        :class="$style.bannerDialog"
        :onOk="onSubmit">
        <ModifyForm
          :hiddenBtn='true'
          :editColumn='editColumn'
          :updateData="updateData"
          labelWidth='100px'
          ref="configModal"
          :class="$style.ModifyForm"
          :temporaryData='modalData'>
          <div slot="timeTamp">
              <el-date-picker
              v-model="repairTime"
              type="datetime"
              unlink-panels
              value-format="timestamp"
              :picker-options="pickerOptions2"
              style="height:40px"
            ></el-date-picker>
          </div>
        </ModifyForm>
      </ModalPanel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'personal:repair:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import { objectFilter } from "@/tools/array";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import SearchSelect from "@/components/SearchSelect";
import { dateFormat } from "@/tools/time";
export default {
  name: "repairIndex",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModalPanel,
    ModifyForm,
    SearchSelect
  },
  data() {
    return {
      intro:{
        title: '',
        content: `用户提交维修申请，维修人员查看并联系用户维修`
      },
      loading:false,
      selectValue: [],
      uid:'',
      visible:false,
      modalData: {},
      tableData: [],
      modalData1: [],
      visible1: false,
      edits:false,
       repairTime: null,
       pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      appointmentTime: [new Date().getTime(), new Date().getTime()],
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      pager: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      name: '',
      operation: true,
      state: '',
      phone: '',
      siteId: '',
      siteList: [],
      editColumn: [
        {
          name: "维修时间",
          prop: "repairTime",
          type: "other",
          width:12,
          required: false,
          slotName:'timeTamp'
        },
        
      ],
    };
  },
  created() {
      let now = new Date().getTime() + 3600 * 1000 * 24
      let year = new Date(now).getFullYear()
      let month = new Date(now).getMonth() 
      let day = new Date(now).getDate()
      let last = new Date().getTime() - 3600 * 1000 * 24 * 6
      let lastYear =  new Date(last).getFullYear() 
      let LastMonth = new Date(last).getMonth() 
      let lastDay = new Date(last).getDate()
      this.appointmentTime = [ new Date(lastYear, LastMonth, lastDay, 0, 0,0), new Date(year, month, day, 0, 0,0)]
      this.queryData();
      this.getSite()
  },
  computed: {
    tableConfig () {
      return {
        selection: false,
        columnConfig: [
        
          {
            label: "站点名称",
            type: "text",
            prop: "siteName",
            align: "center"
          },
          {
            label: "充电桩编码",
            type: "text",
            prop: "sn",
            align: "center"
          },
          {
            label: "联系电话",
            type: "text",
            prop: "phone",
            align: "center"
          },
          {
            label: "地址",
            type: "text",
            prop: "siteAddress",
            align: "center"
          },
           {
            label: "维修图片",
            type: "imgArray",
            prop: "pics",
            align: "center",
            style: 'width: 40px;height: 40px;margin-left:2px'
          },
          {
            label: "维修原因",
            type: "text",
            prop: "reason",
            align: "center",
          },
          {
            label: "状态",
            type: "text",
            prop: "state",
            align: "center",
            // fnc: val => val == 1 ? '维修中': val ==3 ? '维修完成': '等待处理'
          },
          {
            label: "提交时间",
            type: "text",
            prop: "createTime",
            align: "center",
          },
           {
            label: "处理时间",
            type: "text",
            prop: "handleTime",
            align: "center",
          },
          {
            label: "预计维修时间",
            type: "text",
            prop: "orderRepairTime",
            align: "center",
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    async queryData() {
       let page =  this.pager.current
      let endTime = this.appointmentTime ? (dateFormat(this.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : undefined
      let beginTime = this.appointmentTime ? (dateFormat(this.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : undefined
      let siteId =  this.siteId
      let phone = this.phone
      let state = this.state
      let search = objectFilter({ state, page, phone, siteId, beginTime, endTime})
      const res = await request({
        url: "/personal/repair/list",
        method: "POST",
        data: search
      });
      res.page.list.map( item => {
        if(item.pics) {
          let pics =[]
          item.pics.forEach(val => {
            pics.push(this.$baseUrl+val)
          });
          item.pics = pics
        }
      })
      this.tableData = res.page.list
      
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    async getSite() {
      const res = await request({
        url: "/iot/site/select",
        method: "POST",
        data: {type: 9}
      });
      this.siteList = res.list
    },
     //用户
    async onSearch(query){
      if (query !== '') {
          this.loading = true;
          let { list } = await request({
              url: "/wx/user/select",
              method: "POST",
              data:  {
                key: query
              }
            });
            this.loading =  false
            this.selectValue = list.map(item => {
              item.value = item.id+''
              item.label = item.name
              return item
            })
        } else {
          this.selectValue = [];
        }
    },
    searchSelect(key, val){
      this[key] = val;
    },
    pageChange(val) {
      this.pager.current = val;
      this.queryData();
    },
    changeSearch(key, val) {
      this[key] = val;
      this.pager.current = 1;
    },
    editStore(id){
      this.$router.push({ path: "/grate/group/info",query:{id:id} })
    },
    commentDetail(id){
      this.$router.push({ path: "/storeDetail",query:{id:id,type: "toview"} })
    },
   
    onCancel () {
      this.visible = false
    },
    onCancelPass(){
      this.visible1 = false
    },
    onSubmit() {
      this.$refs['configModal'].onSubmit()
    },
    onSubmitPass(){
      this.$refs['configModalPass'].onSubmit()
    },
    edit(rowData) {
      this.uid = rowData.uid
      let title = rowData.state == 0 ? "预计维修时间" : "维修完成时间"
      this.editColumn[0].name = title
      this.modalData = {...rowData}
      if(rowData){
          this.edits = true
      }else{
          this.edits = false
      }
      this.visible = true
    },
    
    async updateData(values){
      let url, msg ,datas
      let repairTime = this.repairTime ? (dateFormat(this.repairTime, "yyyy-MM-dd HH:mm:ss")) : ''
      const {id, state} = values
      if(state ==0){
         url = '/personal/repair/handle'
         datas =  {orderRepairTime:repairTime , id}
      }else{
         url = '/personal/repair/complete'
         datas =  {repairTime , id}
      }
     
      msg = '处理成功'
    let res = await request({
      url: url,
      method: 'POST',
      data: {repairTime, id}
    })
    if (res.code !==0) return
     this.$message.success(msg)
      this.visible = false
      this.queryData()
    },
  }
}
</script>
<style lang='scss' module>
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.selectBox {
  margin: 4px 0;
  :global {
    label {
      font-size: 14px;
      color: #666666;
    }
    .el-input__inner {
      height: 32px;
    }
    .el-input__suffix {
      line-height: 32px;
    }
    .el-date-editor--datetime{
      width: 200px;
    }
  }
}
</style>